package com.tencent.wepay.protocol.domain;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.tencent.wepay.annotation.NotBlank;
import com.tencent.wepay.annotation.NotNull;
import com.tencent.wepay.annotation.Range;
import com.tencent.wepay.handler.ValidationHandler;
import com.tencent.wepay.handler.validation.NotBlankHandler;
import com.tencent.wepay.handler.validation.NotNullHandler;
import com.tencent.wepay.handler.validation.RangeHandler;

public class Validation {
	private final static Map<Class<? extends Annotation>,ValidationHandler> validateRelation=new HashMap<Class<? extends Annotation>,ValidationHandler>(){
		private static final long serialVersionUID = 125549261079622906L;

	{
		put(NotBlank.class,new NotBlankHandler());
		put(Range.class,new RangeHandler());
		put(NotNull.class, new NotNullHandler());
	}};
	public boolean validation(){
		boolean v=true;
		@SuppressWarnings("rawtypes")
		Class clz=getClass();
		Field[] fields=clz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Annotation[] annotations=field.getAnnotations();
			if(annotations.length==0){
				continue;
			}
			for (Annotation annotation : annotations) {
				ValidationHandler handler=validateRelation.get(annotation.annotationType());
				if(handler!=null){
					if(!handler.access(field)){
						v=false;
						continue;
					}
					if(!handler.handler(this, field))
						v=false;
				}
			}
			
		}
		return v;
	}
}
